import { BaseViewProp } from "./BaseViewProp";
import UI_cmp_number from "../../../ui/Main/UI_cmp_number";
import { DataHelper } from "../utils/DataHelper";
import { ViewDrag } from "../view/ViewDrag";

export class PropNumber extends BaseViewProp<UI_cmp_number> {

    public onNumChanged: Laya.Handler;

    private _cacheNum: number;

    private _dragCmp: ViewDrag;

    _OnInited() {
        this.ui.m_value.m_text_input.on(Laya.Event.ENTER, this, this._OnTextInput);
        this._dragCmp = new ViewDrag(this.ui.m_value.m_img_bg);
        this._dragCmp.onDrag = Laya.Handler.create(this, this._OnDragNum, null, false);
    }

    private _OnDragNum(x: number, y: number) {
        this._cacheNum += x * 0.1 + y * 0.1;
        this.ui.m_value.m_text_input.text = DataHelper.NumToStr(this._cacheNum);
        this.onNumChanged?.runWith(this._cacheNum);
        this._UpdateUI();
    }

    private _OnTextInput() {
        let wrapNum = parseFloat(this.ui.m_value.m_text_input.text);
        this.ui.m_value.m_text_input.text = DataHelper.NumToStr(wrapNum);
        if (wrapNum == this._cacheNum) return;
        this.onNumChanged?.runWith(wrapNum);
        this._cacheNum = wrapNum;
        this._UpdateUI();
    }

    _OnDispose() {
        this._dragCmp.Dispose();
        if (this.onNumChanged != null) {
            this.onNumChanged.recover();
            this.onNumChanged = null;
        }
    }

    public SetNum(num: number) {
        if (this._cacheNum == num) return;
        this._cacheNum = num;
        this._UpdateUI();
    }

    private _UpdateUI() {
        this.ui.m_value.m_text_input.text = DataHelper.NumToStr(this._cacheNum);
    }

}